﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb;
using Webdiyer.WebControls.Mvc;

namespace MinistryStandardPlatformWeb.Controllers
{
    [IsLogin]
    public class ClientController : Controller
    {
        //
        // GET: /Client/
        private MSPDataContext context = new MSPDataContext();

        [MenuAuthorized("13")]
        public ActionResult Index()
        {
            var clients = from c in context.InfoClient
                          orderby c.Finsertdate descending
                          select c;

            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                string id = HttpUtility.UrlDecode(Request.QueryString["id"]);
                clients = from c in clients
                          where c.ParentUnitId == id
                          orderby c.Finsertdate descending
                          select c;

            }
            return PartialView(clients.ToPagedList(1, CommonDictionary.PageSize));
        }

        [MenuAuthorized("134")]
        public ActionResult Data(string condition, string unitId, string searchAll, int pageIndex = 1)
        {
            var clients = from c in context.InfoClient
                          orderby c.Finsertdate descending
                          select c;
            if (!string.IsNullOrEmpty(unitId) && searchAll != "on")
            {
                clients = from c in clients
                          where c.ParentUnitId == unitId
                          orderby c.Finsertdate descending
                          select c;

            }
            if (!string.IsNullOrEmpty(unitId) && searchAll == "on")
            {
                List<string> ids = CommonFunctions.GetAllChildrenUnits(unitId, CommonFunctions.GetLoginUser().UserId);
                ids.Add(unitId);
                clients = from r in clients
                          where ids.Contains(r.ParentUnitId)
                          orderby r.Finsertdate descending
                          select r;
            }
            if (!string.IsNullOrEmpty(condition))
            {
                clients = from c in clients
                          where c.ClientName.Contains(condition)
                          orderby c.ParentUnitId,c.Finsertdate descending
                          select c;

            }
            return PartialView(clients.ToPagedList(pageIndex, CommonDictionary.PageSize));
        }

        [MenuAuthorized("131")]
        public ActionResult Create()
        {
            string unitId = HttpUtility.UrlDecode(Request.QueryString["unitId"]);
            string unitName = HttpUtility.UrlDecode(Request.QueryString["unitName"]);
            return View(new InfoClient()
            {
                ParentUnitId = unitId,
                InfoUnit = new InfoUnit()
                {
                    UNITID = unitId,
                    UNITNAME = unitName
                }
            });
        }

        [HttpPost]
        [MenuAuthorized("131")]
        public ActionResult Create(InfoClient client)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    client.ClientID = "CLIE" + CommonFunctions.GetDateTimeStrAnd4BitsRandom();
                    client.Finsertdate = DateTime.Now;
                    client.InUserID = CommonFunctions.GetLoginUser().UserId;
                    context.InfoClient.InsertOnSubmit(client);
                    context.SubmitChanges();
                    ViewBag.Message = "添加成功";
                }
                catch (System.Exception ex)
                {
                    ViewBag.Message = "添加失败," + ex.Message;
                }
            }
            else
            {
                ViewBag.Message = "添加失败";
            }
            return View(client);
        }

        //选择客户的所属单位
        public ActionResult PickParentUnit()
        {
            var units = context.RightsDetails.Where(u => u.UserId == CommonFunctions.GetLoginUser().UserId && u.NodeTYPE == true).Select(u => new { NodeId = u.NodeId, ParentNodeId = u.ParentNodeId, NodeName = u.NodeName });
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var unit in units)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = unit.NodeId;
                node.pId = unit.ParentNodeId;
                node.name = unit.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                if (unit.ParentNodeId == null)
                {
                    node.open = true;
                }
                else
                {
                    node.open = false;
                }
                nodes.Add(node);
            }
            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        public ActionResult HasChildren(string parameters)
        {
            string children = string.Empty;
            if (context.InfoContract.Any(c => c.ClientId == parameters))
            {
                children += "合同";
            }

            if (!string.IsNullOrEmpty(children))
            {
                return Json(new { success = "false", message = "该客户下还存在" + children + ",不能直接删除" });
            }
            else
            {
                return Json(new { success = "true", message = "" });
            }
        }

        [MenuAuthorized("132")]
        public ActionResult Delete(string parameters)
        {
            var client = context.InfoClient.SingleOrDefault(c => c.ClientID == parameters);

            try
            {
                context.InfoClient.DeleteOnSubmit(client);
                context.SubmitChanges();
                return Json(new { success = true, message = "" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [MenuAuthorized("133")]
        public ActionResult Edit(string id)
        {
            var client = context.InfoClient.SingleOrDefault(c => c.ClientID == id);
            return View(client);
        }

        [HttpPost]
        [MenuAuthorized("133")]
        public ActionResult Edit(FormCollection form)
        {
            try
            {
                var clientToUpdate = context.InfoClient.SingleOrDefault(c => c.ClientID == form["ClientID"]);
                UpdateModel(clientToUpdate, form.ToValueProvider());
                context.SubmitChanges();
                ViewBag.Message = "修改成功";

                return View(clientToUpdate);
            }
            catch (System.Exception ex)
            {
                ViewBag.Message = "修改失败," + ex.Message;
                return View(new InfoClient());
            }

        }
    }
}
